import { Directive, HostListener, ElementRef, Renderer2, Input } from '@angular/core';
import { DragDropService } from '../drag-drop.service';
// 拖动指令
@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[app-draggable][draggedClass][dragTag][dragData]'
})
export class DragDirective {

  private _isDraggable = false; // 是否可以拖动

  @Input('app-draggable')
  set isDraggable(value: boolean) {
    this._isDraggable = value;
    this.rd.setAttribute(this.elementRef.nativeElement, 'draggable', `${value}`)
  }

  get isDraggable() {
    return this._isDraggable;
  }

  @Input() draggedClass: string;
  @Input() dragTag: string;
  @Input() dragData: any;
  constructor(
    private elementRef: ElementRef,
    private rd: Renderer2,
    private service: DragDropService) { }
  // 监听开始拖动
  @HostListener('dragstart', ['$event'])
  onDragStart(ev: Event) {
    console.log('dragstart');
    // 判断是否是当前元素出发的事件
    if (this.elementRef.nativeElement === ev.target) {
      // 往 this.ele 添加一个class
      this.rd.addClass(this.elementRef.nativeElement, this.draggedClass);
      this.service.setDragData({ tag: this.dragTag, data: this.dragData });
    }
  }

  // 监听拖动停止
  @HostListener('dragend', ['$event'])
  onDragEnd(ev: Event) {
    if (this.elementRef.nativeElement === ev.target) {
      // 从 this.ele 移除一个class
      this.rd.removeClass(this.elementRef.nativeElement, this.draggedClass);
    }
  }
}
